package com.ruoyi.common.utils.file;

import com.ruoyi.common.config.MinioConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import io.minio.*;
import io.minio.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
@Service
public class MinioFileUploadUtils {
    @Resource
    MinioClient minioClient;
    @Resource
    MinioConfig minioConfig;
    public AjaxResult bucketExists(String bucketName){
        try{
            return AjaxResult.success(minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build()));
        } catch (Exception e){
            AjaxResult.error("当前桶不存在：{}",bucketName);
        }
        return null;
    }

    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        String originalFilename = file.getOriginalFilename();
        String upLoadFile = UUID.randomUUID()+"-"+file.getOriginalFilename() ;
        InputStream inputStream = file.getInputStream();
        FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
        // 缓冲池10M
        PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                .bucket(minioConfig.getBucketName())
                .stream(inputStream, -1, 1024 * 1024 * 10)
                .object(upLoadFile)  // 文件名称
                .build();
        AjaxResult ajax = AjaxResult.success();
        // 上传文件
        minioClient.putObject(putObjectArgs);

        String presignedObjectUrl = getUploadFileUrl(upLoadFile);
        ajax.put("url", presignedObjectUrl);
        ajax.put("fileName", presignedObjectUrl);
        ajax.put("newFileName", originalFilename);
        ajax.put("originalFilename", file.getOriginalFilename());
        return ajax;
    }

    public String getUploadFileUrl(String fileName){
        try{
            GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(fileName)
                    .method(Method.GET)
                    .build();
            String presignedObjectUrl = minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs);
            return presignedObjectUrl;
        } catch (Exception e){
            log.error("获取上传文件地址失败：{}",fileName,e);
            return null;
        }

    }
}
